# apps/exam_papers/models.py
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator

from apps.tenants.models import Tenant
from apps.users.models import QBUser
from apps.subjects.models import Subject


class ExamPaper(models.Model):
    """
    试卷模型
    对应数据库表: qb_exam_papers
    """

    # 试卷状态选择项
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('published', '已发布'),
        ('archived', '归档'),
    ]

    title = models.CharField(
        max_length=200,
        verbose_name="试卷名称",
        help_text="试卷标题，如：高一数学月考卷"
    )

    description = models.TextField(
        null=True,
        blank=True,
        verbose_name="试卷说明",
        help_text="试卷的描述或注意事项"
    )

    total_score = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=100.00,
        verbose_name="总分",
        help_text="试卷满分，如：100.00"
    )

    duration_minutes = models.IntegerField(
        default=90,
        verbose_name="考试时长（分钟）",
        help_text="考试持续时间，单位：分钟"
    )

    difficulty = models.SmallIntegerField(
        default=3,
        validators=[MinValueValidator(1), MaxValueValidator(5)],
        verbose_name="难度等级",
        help_text="难度等级 1-5（1:简单, 5:困难），由应用层校验"
    )

    creator = models.ForeignKey(
        QBUser,
        on_delete=models.CASCADE,
        verbose_name="创建人",
        help_text="试卷的创建用户",
        db_index=True
    )

    subject = models.ForeignKey(
        Subject,
        on_delete=models.CASCADE,
        verbose_name="科目",
        help_text="所属科目",
        db_index=True
    )

    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='draft',
        verbose_name="状态",
        help_text="试卷当前状态：草稿、已发布、归档",
        db_index=True
    )

    generated_from = models.JSONField(
        null=True,
        blank=True,
        verbose_name="生成配置",
        help_text="智能组卷参数，如：知识点分布、难度比例等，JSON 格式"
    )

    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name="创建时间"
    )

    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name="更新时间"
    )

    tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True, db_index=True, verbose_name="租户")

    class Meta:
        db_table = 'qb_exam_papers'
        verbose_name = "试卷"
        verbose_name_plural = "试卷管理"
        indexes = [
            models.Index(fields=['tenant'], name='idx_exam_paper_tenant'),
            models.Index(fields=['creator'], name='exam_papers_idx_creator_id'),
            models.Index(fields=['subject'], name='exam_papers_idx_subject_id'),
            models.Index(fields=['status'], name='exam_papers_idx_status'),
            models.Index(fields=['-created_at'], name='idx_exam_paper_created_at'),
        ]
        # 提示：Django 不直接支持 ENGINE 和 CHARSET
        # 需在迁移文件中通过 RunSQL 手动设置
        # 或确保数据库默认字符集为 utf8mb4_unicode_ci

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        """
        重写 save 方法（可选扩展）
        目前 Django 的 auto_now 和 auto_now_add 已处理时间字段
        若需额外逻辑（如日志、缓存更新），可在此添加
        """
        super().save(*args, **kwargs)